package com.dw.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dw.core.entity.Permission;
import com.dw.core.entity.Role;
import com.dw.core.entity.RolePermission;
import com.dw.core.mapper.IPermissionMapper;
import com.dw.core.service.IPermissionService;
import com.dw.core.service.IRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhangjing
 * @date 2020/8/21 14:54
 * @Description
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<IPermissionMapper, Permission> implements IPermissionService {

    @Autowired
    IRolePermissionService rolePermissionService;

    /**
     * get perm keys by roles
     *
     * @param roles
     * @return
     */
    @Override
    public Set<String> getPermKeysByRoles(List<Role> roles) {

        Set<String> temp = new HashSet<>();
        if (CollectionUtils.isEmpty(roles)) {
            return temp;
        }
        Set<Long> roleIds = roles.stream().map(Role::getId).collect(Collectors.toSet());

        // 角色用的所有权限
        List<RolePermission> rolePermissions = rolePermissionService.list(new LambdaQueryWrapper<RolePermission>().in(RolePermission::getRoleId, roleIds));
        if (CollectionUtils.isEmpty(rolePermissions)) {
            return temp;
        }
        Set<Long> permIds = rolePermissions.stream().map(RolePermission::getPermId).collect(Collectors.toSet());

        List<Permission> permissions = this.list(new LambdaQueryWrapper<Permission>().in(Permission::getId, permIds));
        return permissions.stream().map(Permission::getPermKey).collect(Collectors.toSet());
    }
}
